package com.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.mapper.GoodsMapper;
import com.shop.mapper.ShopcartMapper;
import com.shop.pojo.Goods;
import com.shop.pojo.Shopcart;
import com.shop.service.ShopcartService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class ShopcartServiceImpl implements ShopcartService {
    @Autowired
    private ShopcartMapper shopcartMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public Boolean sameGoods(Shopcart shopcart) {
        QueryWrapper<Shopcart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",shopcart.getUid());
        List<Shopcart> list = shopcartMapper.selectList(wrapper);
        for (Shopcart s:list) {
            if (s.getGid().equals(shopcart.getGid())){
                return true;
            }
        }
        return false;
    }

    @Override
    public void add(Shopcart shopcart) {
        shopcartMapper.insert(shopcart);
    }

    @Override
    public List<Shopcart> findAll(Integer uid) {
        QueryWrapper<Shopcart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",uid);
        List<Shopcart> list = shopcartMapper.selectList(wrapper);
        for (Shopcart s:
             list) {
            Integer gid = s.getGid();
            QueryWrapper<Goods> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("goods_id",gid);
            Goods goods = goodsMapper.selectOne(wrapper1);
            s.setPicture(goods.getPicture());
            s.setGoodsName(goods.getName());
            s.setSumPrice((double) (goods.getPrice()*s.getNumber()));
        }
        return list;
    }

    @Override
    public void delete(Integer uid, Integer gid) {
        QueryWrapper<Shopcart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",uid).eq("goods_id",gid);
        shopcartMapper.delete(wrapper);
    }

    @Override
    public List<Shopcart> findCheckGoods(String gids,Integer uid) {
        String[] split = gids.split(",");
        List<Integer> integers = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            integers.add(Integer.parseInt(split[i]));
        }
        QueryWrapper<Shopcart> wrapper = new QueryWrapper<>();
        wrapper.in("goods_id",integers).eq("user_id",uid);
        List<Shopcart> list = shopcartMapper.selectList(wrapper);
        for (Shopcart s:
             list) {
            QueryWrapper<Goods> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("goods_id",s.getGid());
            Goods goods = goodsMapper.selectOne(wrapper1);
            s.setPicture(goods.getPicture());
            s.setGoodsName(goods.getName());
        }
        return list;
    }


}
